package cn.dansj.common.utils.spring.context;

import cn.dansj.common.utils.transfer.Transformation;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public abstract class GetEnvironment {
    private static Map<String, String> map;

    static {
        getEnvironmentMapData();
    }

    static void getEnvironmentMapData() {
        ConfigurableEnvironment environment = ApplicationContextProvider.getBean(ConfigurableEnvironment.class);
        map = StreamSupport.stream(environment.getPropertySources().spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource)
                .map(ps -> ((EnumerablePropertySource<?>) ps).getPropertyNames()).flatMap(Arrays::stream).distinct().collect(Collectors.toMap(Function.identity(), (e) -> Transformation.nvl(environment.getProperty(e), "")));
    }

    public static Map<String, String> get() {
        return map;
    }

    public static String get(String key) {
        return map.get(key);
    }

    public static String get(String key, String defaultValue) {
        return Transformation.lambdaTryCatch(() -> Transformation.nvl(map.get(key), defaultValue), () -> defaultValue);
    }

    public static int getInt(String key) {
        return Transformation.parseInt(key);
    }

    public static int getInt(String key, int defaultValue) {
        return Transformation.parseInt(key, defaultValue);
    }
}